<template>
	<Dialog :visible="showDialog" :styleConfig="styleConfig" :handleClose="handleClose">
		<view v-for="(item, index) in chatList" :key="index" class="chat-container"
			@click.stop="handleContentClick(item)">
			<image class="item-icon" v-if="item.imgType === 'SINGLE'" src="../../assets/icon/singlePerson.svg" />
			<image class="item-icon" v-else src="../../assets/icon/multiPerson.svg" />
			<view>{{ item.content }}</view>
		</view>
	</Dialog>
	<view class="note">
		<view class="note-header">
			<view class="note-header_tabs u-flex">
				<view class="search-btn" @click="$goPage('/staff/imSearch')" v-if="false">
					<u-icon name="search" color="#9F9F9F" size="44"></u-icon>
				</view>
				<u-tabs :list="tabList" @change="tabChange" :current="current" inactive-color="#8D8D8D" bg-color=""
					class="tab-content" bar-width="150" item-width="270" bar-height="8" font-size="32"></u-tabs>
				<view class="note-add_btn" @click="$goPage('/staff/search')"  v-if="vuex_user.type == 1">
					<i class="icon icon-add-friend"></i>
				</view>
			</view>
		</view>
	</view>
	<view class="TUI-conversation note-tab container-conversation" v-show="current == 0">
		<view class="note-section">
			<view class="note-item u-flex" @click="$goPage('/note/inform', {type:2, unreadTotal: unreadTotal})">
				<view class="note-item_avatar">
					<u-image width="72rpx" height="72rpx" border-radius="16rpx" src="/static/images/system.png">
					</u-image>
					<u-badge type="error" :count="msgCount" :offset="[-8,-8]" size="mini"></u-badge>
				</view>
				<view class="note-item_content u-flex-1">
					<view class="note-item_content--name">{{$t('chat.btn_notify')}}</view>
				</view>
			</view>
		</view>

		<!-- <view class="create-group" @click="handleShow"> + 发起聊天</view> -->
		<TUIConversationList :currentID="currrentConversationID" :conversationList="conversationList"
			@handleGotoItem="handleCurrentConversation" />
	</view>
	<view class="note-tab" v-show="current == 1">
		<movable-area class="t-conversation-item-container note-section">
			<movable-view class="t-conversation-item" direction="horizontal" @click="$goPage('/note/group')"
				damping="100">
				<view class="avatar-box">
					<image class="t-conversation-item-avatar" src="/static/static/assets/gruopavatar.svg">
					</image>
				</view>
				<view class="t-conversation-item-content">
					<label class="tui-conversation-item-name">{{$t('chat.chat_group')}}</label>
				</view>
			</movable-view>
		</movable-area>
		<view v-if="!isEmpty" v-for="(data,key) in friendList" :key="key">
			<view class="u-m-l-24 user-title">{{ key }}</view>
			<movable-area v-for="(item,index) in data" :key="index" class="t-conversation-item-container">
				<movable-view class="t-conversation-item" direction="horizontal" @change="handleTouchMove"
					@click="goUser(item.FriendTimUserId)" damping="100" :x="xScale">
					<view class="avatar-box">
						<image class="t-conversation-item-avatar"
							:src="item.FriendAvatar == '' ? '../../static/images/avatar.jpg': item.FriendAvatar">
						</image>
					</view>
					<view class="t-conversation-item-content">
						<label class="tui-conversation-item-name">{{item.FriendName}}</label>
					</view>
				</movable-view>
			</movable-area>
		</view>
		<view class="empty-text" v-if="isEmpty">{{ $t('chat.empty_txt')}}</view>
	</view>
</template>
<script lang="ts">
	import {
		defineComponent,
		reactive,
		toRefs,
		computed,
		onMounted,
		getCurrentInstance
	} from "vue";
	import {
		onNavigationBarButtonTap,
		onShow,
		onUnload
	} from "@dcloudio/uni-app";
	import TUIConversationList from "./conversation-list";
	import Dialog from "./components/dialog.vue";
	import store from "../../TUICore/store";
	import newstore from '@/store/index';
	import {
		TUIConversationServer,
		TUIProfileServer
	} from "../../TUICore/server";
	import {
		useI18n
	} from "vue-i18n";
	import indexStore from '@/store/index.js';
	import pinyin from 'js-pinyin';
	import homeStorage from "@/utils/storage.js";
	import pageMixin from '@/utils/tabBarMixin';
	const TUIConversation = defineComponent({
		mixins: [pageMixin],
		name: "TUIConversation",
		components: {
			TUIConversationList,
			Dialog,
		},

		setup(props) {
			const that = getCurrentInstance()
			const userID = that.proxy.$store.state.vuex_user.uid || 0;
			console.log("userID", userID);
			if (userID === 0) {
				uni.reLaunch({
					url: '/pages/login/index',
				});
				return;
			}
			
			const timStore = store.state.timStore;
			uni.$TUIKit.TUIConversationServer = new TUIConversationServer();
			uni.$TUIKit.TUIProfileServer = new TUIProfileServer();
			const {
				t
			} = useI18n();
			// const { t } = uni.$TUIKit.config.i18n.useI18n();
			const data: any = reactive({
				conversationList: computed(() => timStore.conversationList),
				currrentConversationID: "",
				vuex_user: indexStore.state.vuex_user,
				open: false,
				searchUserID: "",
				selectedList: [],
				searchUserList: [],
				step: 1,
				showDialog: false,
				current: 0,
				msgCount: 0,
				unreadTotal: 0,
				friendList: {},
				isEmpty: false,
				xScale: 0,
				lock: false,
				last: 0,
				item: {
					flow: "out",
					status: "success",
				},
				styleConfig: {
					width: "150px",
					// height: '160px',
					padding: "16px 16px 0px",
					top: "8px",
					right: "8px",
				},
				tabList:computed(()=>[{
						'name': t('chat.chat')
					},
					{
						'name': t('chat.contact')
					}
				]) ,
				chatList: [{
						imgType: "SINGLE",
						type: uni.$TIM.TYPES.CONV_C2C,
						id: 1,
						content: "发起会话",
					},
					{
						imgType: "GROUP",
						type: uni.$TIM.TYPES.GRP_WORK,
						id: 1,
						content: "工作群",
					},
					{
						imgType: "GROUP",
						type: uni.$TIM.TYPES.GRP_PUBLIC,
						id: 2,
						content: "社交群",
					},
					{
						imgType: "GROUP",
						type: uni.$TIM.TYPES.GRP_MEETING,
						id: 3,
						content: "会议群",
					},
				],
			});

			onUnload(() => {
				uni.$TUIKit.TUIConversationServer.destroyed();
			});

			onNavigationBarButtonTap(() => {
				data.showDialog = !data.showDialog;
			});
			onShow(() => {
				// console.log('执行----------------')
				newstore.commit('checkUserLogin');
				store.commit("timStore/setConversationID", "");
				getServerConversationList();
			});

			//获取服务上的会话列表数据
			const getServerConversationList = () => {

				// console.log("进来了呀")
				that.proxy.$http.get('/mgr/user/friend/data', {}).then(res => {
					// console.log("数据呢", res)
				});
				that.proxy.$http.get('/msg/system/count1', {
				}).then(res => {
					data.msgCount = res
					})
			};

			// 切换当前会话
			const handleCurrentConversation = (value: any) => {
				// console.log("value", value)
				data.currrentConversationID = value.conversationID;
				store.commit("timStore/setConversationID", value.conversationID);
				var name = ''
				switch (value.type) {
					case uni.$TIM.TYPES.CONV_C2C:
						name = value?.userProfile.nick || value?.userProfile?.userID || "";
						uni.navigateTo({
							url: `../TUIChat/index?conversationName=${name}`,
						});
						break;
					case uni.$TIM.TYPES.CONV_GROUP:
						name = value.groupProfile.name || value?.groupProfile?.groupID || "";
						uni.navigateTo({
							url: `../TUIChat/index?conversationName=${name}&conversationId=${value?.groupProfile?.groupID}`,
						});
						break;
					case uni.$TIM.TYPES.CONV_SYSTEM:
						name = "系统通知";
						uni.navigateTo({
							url: `../TUIChat/index?conversationName=${name}`,
						});
						break;
				}
				// console.log("value.conversationID", value)
				uni.$TUIKit.TUIConversationServer.setMessageRead(value.conversationID);
				const curConversation = data.conversationList.filter((item: any) => {
					return item.conversationID === value.conversationID;
				});
				store.commit("timStore/setConversation", curConversation);
				uni.$TUIKit.TUIConversationServer.getConversationProfile(
					value.conversationID
				).then((res: any) => {
					// 通知 TUIChat 关闭当前会话
					store.commit("timStore/setConversation", res.data.conversation);
					// uni.$TUIKit.getStore()['TUIChat'].conversation = res.data.conversation;
				});
			};

			const handleShow = () => {
				data.showDialog = true;
			};

			// dialog 内部有效区域点击
			const handleContentClick = (item) => {
				data.showDialog = false;
				uni.navigateTo({
					url: `../TUIConversation/create?title=${item.content}&type=${item.type}`,
				});
			};
			// 关闭 dialog
			const handleClose = () => {
				data.showDialog = false;
			};
			const handleItemName = (item: any) => {
				let name = "";
				switch (item.type) {
					case uni.$TIM.TYPES.CONV_C2C:
						name = item?.userProfile.nick || item?.userProfile?.userID || "";
						break;
					case uni.$TIM.TYPES.CONV_GROUP:
						name = item.groupProfile.name || item?.groupProfile?.groupID || "";
						break;
					case uni.$TIM.TYPES.CONV_SYSTEM:
						name = "系统通知";
						break;
				}
				return name;
			};

			// Tab 切换事件
			const tabChange = (index) => {
				console.log("index", index)
				data.current = index
				if (data.current == 1) {
					getUserFriendList();
				} else if (data.current == 0) {
					// this.subscribeGroup();
					// this.listenConversationUpdate(); //监听会话列表变化
				}
			};

			// 获取好友列表数据
			const getUserFriendList = () => {
				console.log("进来获取了")
				
				//获取当前网络状况
				let key = 'user_friend_' + userID;
				uni.getNetworkType({
					success: function(res) {
						console.log("res.networkType", res.networkType)
						if (res.networkType == 'none') {
							
							let friendData = uni.getStorageSync(key)||[]
							console.log("friendData", friendData)
							if (friendData != '{}') {
								console.log("本地缓存数据", friendData);
								data.friendList = friendData;
								console.log("data.friendList", data.friendList)
							} else {
								data.isEmpty = true
							}
							
						} else {
							
							that.proxy.$http.get('/mgr/user/friend/data', {}).then(res => {
								console.log("数据呢", res)
								if (res.length == 0) {
									data.isEmpty = true
								}
								data.friendList = sortMember(res);
								
								//本地存储
								uni.setStorageSync(key,data.friendList)
								
							});
						}
					},
				});
			};

			// 排序好友列表数据
			const sortMember = (arr) => {

				var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
				var resList = {} //排序分类后的对象
				let pattern1 = new RegExp("[\u4E00-\u9FA5]+"); //中文
				let pattern2 = new RegExp("[A-Za-z]+"); //英文	
				var listKey =[]
				letters.map((item, i) => {
					listKey =[]
					arr.forEach(item1 => {
						//验证改昵称是以中文、英文还是其他字符开头
						let firstStr = item1.FriendName.substring(0, 1)

						let str = '' //定义首字母

						if (pattern1.test(firstStr)) {
							//如果以中文开头，则转换为拼音,并获取首字母

							str = pinyin.getFullChars(firstStr).substring(0, 1)
						} else if (pattern2.test(firstStr)) {
							//如果以英文字母开头

							str = firstStr.toUpperCase()
						}
						if (str == item) {
							listKey.push(item1)
						}
					})
					if(listKey.length !=0){
						resList[item] = listKey
						// resList[item].push(listKey)
					}

				})

				//其他字符开头的成员					
				arr.forEach(item1 => {
					//验证改昵称是以中文、英文还是其他字符开头
					let firstStr = item1.FriendName.substring(0, 1)
					let str = '' //定义首字母

					if (!pattern2.test(firstStr) && !pattern1.test(firstStr)) {
						//如果以中文开头，则转换为拼音,并获取首字母

						resList['#'] = []
						resList['#'].push(item1)
					}
				})
				console.log("1111", resList)
				return resList
			};


			const handleTouchMove = (e) => {
				if (!data.lock) {
					data.last = e.detail.x;
					data.lock = true;
				}

				if (data.lock && e.detail.x - data.last < -5) {
					data.xScale = -75
					setTimeout(() => {
						data.lock = false;
					}, 2000);
				} else if (data.lock && e.detail.x - data.last > 5) {
					data.xScale = 0
					setTimeout(() => {
						data.lock = false;
					}, 2000);
				}
			};

			// 跳转用户个人主页
			const goUser = (uid) => {
				console.log("来跳转了")
				if (uid > 1) {
					uni.navigateTo({
						url: '/pages/user/index?uid=' + uid + '&isFromContact=1'
					});
				}
			};

			return {
				...toRefs(data),
				getServerConversationList,
				handleCurrentConversation,
				handleContentClick,
				handleItemName,
				handleClose,
				handleShow,
				tabChange,
				handleTouchMove,
				goUser,
			};
		},
	});
	export default TUIConversation;
</script>

<style lang="scss" scoped>
	 @import "./index.css";
	.TUI-conversation {
		.create-group {
			font-weight: 800px;
			padding: 10px;
			font-size: 14px;
			text-align: center;
		}
	}

	.chat-container {
		display: flex;
		align-items: center;
		margin-bottom: 16px;
		color: #444444;

		.item-icon {
			display: inline-block;
			width: 21px;
			height: 21px;
			margin-right: 12px;
		}
	}

	@keyframes appear {
		0% {
			opacity: 0
		}

		25% {
			opacity: 0.7
		}

		100% {
			opacity: 1
		}
	}

	.note {
		// padding-bottom: 88rpx;
		padding-top: calc(130rpx + var(--status-bar-height));
	}

	.user-title {
		color: #9a9a9a;
		font-size: 26rpx;
	}

	.empty-text {
		position: absolute;
		top: 600rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	.note-header {
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
		padding-top: var(--status-bar-height);
		background-color: #EFEFEF;
	}

	.note-header_tabs {
		width: 80%;
		padding: 30rpx 0 0;
		margin: 0 auto;
	}

	.line {
		width: 2rpx;
		height: 26rpx;
		background-color: #cdcdcd;
	}

	.line1 {
		position: absolute;
		left: 140rpx;
	}

	.line2 {
		position: absolute;
		left: 50%;
	}

	.line3 {
		position: absolute;
		right: 140rpx;
	}

	.tab {
		text-align: center;
		color: #8D8D8D;
	}

	.tab-content {
		width: 100%;
		font-size: 32rpx;
		font-family: Adobe Heiti Std;
		font-weight: normal;
		color: #000000;
		background-color: transparent;
	}

	.u-tab-bar {
		margin-top: 10rpx;
	}

	.tab-active {
		color: #000;
	}

	.search-btn {
		position: absolute;
		left: 40rpx;
	}

	.note-add_btn {
		position: absolute;
		right: 50rpx;
		padding-bottom: 10rpx;
	}

	.icon-add-friend {
		color: #9F9F9F;
		font-size: 38rpx;

	}

	.head-tab-icon {
		margin-right: 17rpx;
		font-size: 36rpx;
	}

	.head-tab-text {
		font-size: 35rpx;
		font-family: Adobe Heiti Std;
		font-weight: normal;
		color: #8D8D8D;
		line-height: 40rpx;
	}

	.note-section {
		margin-bottom: 20rpx;
		margin-top: -10rpx;
	}

	.note-item {
		background-color: #fff;
		height: 106rpx;
		padding: 0 24rpx 0 18rpx;

		&_avatar {
			position: relative;
			margin-right: 24rpx;
		}

		&_content {
			height: 100%;
			display: flex;
			justify-content: center;
			flex-direction: column;

			&--name {
				font-size: 32rpx;
			}

			&--text {
				font-size: 24rpx;
				color: #949C9E;
			}
		}

		&_time {
			font-size: 24rpx;
			height: 76rpx;
			color: #949C9E;
		}
	}


	page {
		height: 100%;
	}

	.conversations {
		width: 750rpx;
		overflow-x: hidden;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		height: 100%;

	}

	.tooltips {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		display: inline-block;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 -10rpx 20rpx #d9dcdc, 10rpx 0 20rpx #d9dcdc, 0 10rpx 20rpx #d9dcdc, -10rpx 0 20rpx #d9dcdc;
		user-select: none;
		-webkit-touch-callout: none;

		&.tooltips-active {
			transition: transform 0.2s ease-in-out 0s;
			transform: scale(1, 1);
		}

		&.tooltips-inactive {
			transition: transform 0s ease-in-out 0s;
			transform: scale(0, 0);
		}

		.tooltips-item {
			padding: 24rpx 60rpx;
			font-size: 34rpx;
			font-weight: 400;
		}

		.current-tip {
			background-color: #f1f1f1;
		}
	}

	.conversations .scroll-item {
		height: 152rpx;
		display: flex;
		align-items: center;
		padding-left: 32rpx;
	}

	.conversations .current-item {
		background-color: #e7eaea;
	}

	.conversations .scroll-item .head-icon {
		width: 96rpx;
		height: 96rpx;
		margin-right: 28rpx;
		border-radius: 16rpx;
	}

	.conversations .scroll-item_info {
		height: 151rpx;
		width: 590rpx;
		padding-right: 32rpx;
		box-sizing: border-box;
		border-bottom: 1px solid #EFEFEF;
	}

	.conversations .scroll-item_info .item-info-top {
		margin-top: 20rpx;
		padding-bottom: 16rpx;
		height: 60rpx;
		line-height: 60rpx;
		display: flex;
		justify-content: space-between;

	}

	.conversations .item-info-top_name {
		font-size: 34rpx;
		color: #262628;
		width: 460rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.conversations .item-info-top_time {
		font-size: 26rpx;
		margin-top: -8rpx;
		color: rgba(179, 179, 179, 0.8);
		font-family: Source Han Sans CN;
		white-space: nowrap;
	}

	.conversations .item-info-bottom {
		height: 40rpx;
		line-height: 40rpx;
		overflow: hidden;
	}

	.conversations .item-info-bottom-item {
		display: flex;
		justify-content: space-between;
	}

	.item-info-bottom .item-info-top_content {
		font-size: 30rpx;
		color: #b3b3b3;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;

	}

	.item-info-bottom .item-info-bottom_action {
		width: 50rpx;
		height: 50rpx;
		font-size: 20rpx;
		background: url("../../static/images/action.png") no-repeat center;
		background-size: 28rpx 30rpx;
	}

	.no-conversation {
		width: 100%;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		color: #9D9D9D;
	}

	.item-head {
		position: relative;
	}

	.item-head .item-head_unread {
		padding: 6rpx;
		background-color: #EE593C;
		color: #FFFFFF;
		font-size: 24rpx;
		line-height: 28rpx;
		border-radius: 24rpx;
		min-width: 24rpx;
		min-height: 24rpx;
		text-align: center;
		position: absolute;
		top: 0;
		right: 15rpx;
	}

	.action-container {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.action-container .layer {
		position: absolute;
		top: 0;
		left: 0;
		background: rgba(51, 51, 51, 0.5);
		width: 100%;
		height: 100%;
		z-index: 99;
	}

	.action-box {
		width: 400rpx;
		height: 240rpx;
		background: #ffffff;
		position: relative;
		z-index: 100;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.action-item {
		text-align: center;
		line-height: 120rpx;
		font-size: 34rpx;
		color: #262628;
		border-bottom: 1px solid #EFEFEF;
	}

	.unread-text {
		color: #618DFF;
	}
</style>
